<?php

namespace app\index\controller;

use app\common\model\User;
use app\common\validate\LoginValidate;
use think\Controller;
use think\helper\Hash;
use think\Request;
use think\facade\Session;

class Login extends Controller
{

    public function index()
    {
        return view();
    }

    public function loginHandler(Request $request)
    {
        $userData = $request->only(['username', 'password']);
        $validator = new LoginValidate;
        ! $validator->check($userData) && $this->error($validator->getError());

        $user = User::where('username', $userData['username'])->find();
        ! $user && $this->error('用户不存在');

        // 密码验证
        ! Hash::check($userData['password'], $user->password) && $this->error('密码错误');

        // session
        Session::set('user_id', $user->id);

        $this->success('登陆成功', Session::get('login_referer') ?: '/');
    }

    public function logout()
    {
        Session::delete('user_id');
        $this->success('已安全退出', '/');
    }

}
